import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * servletContext实现网站访问计数
 */
public class S11_OrderServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取到ServletContext对象
        ServletContext servletContext = super.getServletContext();
        System.out.println("OrderServlet servletContext = " + servletContext
                        + " 运行类型=" + servletContext.getClass());

//        //从servletContext获取 visit_count 属性 k-v
//        Object visitCount = servletContext.getAttribute("visit_count");
//        //判断visit_count是否为空
//        if (visitCount == null) {   //说明是第一次访问
//            servletContext.setAttribute("visit_count", 1);
//            visitCount = 1;
//        } else {    //第二次或以后
//            //取出visit_count的值，再+1
//            visitCount = Integer.parseInt(visitCount.toString()) + 1;
//            //放回 servletContext
//            servletContext.setAttribute("visit_count", visitCount);
//        }
        int visitCount = S13_WebUtils.visitCount(servletContext);
        //输出显示
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.print("<h1>网站被访问的次数是</h1>" + visitCount + "</h1>");
        writer.flush();
        writer.close();
    }
}
